<?php

class OfferController extends ToolsBaseController
{
	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow', // allow authenticated user to perform below actions
				//'actions'=>array('logout'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				//'actions'=>array('logout'),
				'users'=>array('*'),
			),
		);
	}
	
	public function actionIndex()
	{
		if (!Yii::app()->request->isAjaxRequest) {
			$this->render('index');
			Yii::app()->end();
		}
		
		//handle page=?
		$page_size = Yii::app()->params['pageSize'];
		$current_page = Yii::app()->request->getParam('page', 1);
		$offset = ($current_page - 1) * $page_size;
		$sql_limit = " LIMIT {$offset}, {$page_size} ";
		
		$params = array();
		$sql_where = '';
		
		//q=?
		$q = Yii::app()->request->getPost('q');
		if (!empty($q)) {
			$sql_where .= ' AND (s.id_merchant=:qq
				OR s.content LIKE :qlike OR m.name LIKE :qlike OR m.address LIKE :qlike OR m.biz_area LIKE :qlike OR m.phone LIKE :qlike) ';
			$params[':qq'] = $q;
			$params[':qlike'] = "%{$q}%";
		}
		
		//post admin
		$id_admin = Yii::app()->request->getPost('id_admin');
		if (!empty($id_admin)) {
			$sql_where .= ' AND s.id_admin=:id_admin ';
			$params[':id_admin'] = $id_admin;
		}
		
		//post filter_week=?
		$filter_week = Yii::app()->request->getPost('filter_week', 0);
		if ($filter_week > 0 and $filter_week < 8) {
			$sql_where .= ' AND s.week_days LIKE :week_days';
			$params['week_days'] = "%{$filter_week}%";
		}
		//post filter_status
		$filter_status = Yii::app()->request->getPost('filter_status', '');
		if ($filter_status === '1') {
			$sql_where .= ' AND s.status=1';
		} else if ($filter_status === '0') {
			$sql_where .= ' AND (s.status is null OR s.status=0)';
		}
		//post filter_date
		$filter_date = Yii::app()->request->getPost('filter_date', '');
		if ($filter_date === '0') {
			//current
			$sql_where .= ' AND s.start_date<NOW() AND s.end_date>NOW()';
		} else if ($filter_date === '1') {
			//upcoming
			$sql_where .= ' AND s.start_date>NOW()';
		} else if ($filter_date === '2') {
			//expired
			$sql_where .= ' AND s.end_date<NOW()';
		} else if ($filter_date === '3') {
			//current + upcoming
			$sql_where .= ' AND s.end_date>NOW()';
		}
		
		$sql_orderby = ' ORDER BY s.update_timestamp DESC ';
		$sql_offer = 'SELECT s.id, s.id_merchant, s.url_picture, m.url_logo, m.url_offer_img, s.content,
			s.show_price, s.price, s.value, s.discount,
			s.show_hours, s.start_hour, s.end_hour, s.week_days, s.status, s.type,
			(NOW() > s.end_date) AS completed, UNIX_TIMESTAMP(s.published_time) AS uts_published_time,
			UNIX_TIMESTAMP(s.start_date) AS uts_start_date, UNIX_TIMESTAMP(s.end_date) AS uts_end_date,
			SUM(d.reach) as reach, SUM(d.clicks) as clicks, SUM(d.notifications) as notifications, SUM(d.spread) as spread, SUM(d.redeems) as redeems,
			s.id_admin, a.name AS admin_name, m.name
			FROM tbl_merchant_special s
			INNER JOIN tbl_merchant_account m ON m.id=s.id_merchant
			LEFT JOIN tbl_merchant_special_report_day d ON d.id_special=s.id
			LEFT JOIN tbl_sys_admin_account a ON s.id_admin=a.id
			WHERE s.trash=0 ' . $sql_where
			. ' GROUP BY s.id '
			. $sql_orderby
			. $sql_limit;
		$sql_count = 'SELECT COUNT(s.id) AS total FROM tbl_merchant_special s INNER JOIN tbl_merchant_account m ON m.id=s.id_merchant
			WHERE s.trash=0 ' . $sql_where;
		
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_offer);
		$rows = $command->queryAll(true, $params);
		$command = $connection->createCommand($sql_count);
		$aTotal = $command->queryRow(true, $params);
		$connection->active = false;
		
		//set pager
		$pages = new CPagination($aTotal['total']);
		$pages->setPageSize($page_size);
		if (Yii::app()->request->isAjaxRequest) {
			$this->renderPartial('_list', array('model' => $rows, 'pages' => $pages));
		} else {
			$this->render('index', array('model' => $rows, 'pages' => $pages));
		}
	}
	
	/**
	 * Create or edit an offer with form page.
	 */
	public function actionForm($id = null) {
		$model = empty($id) ? new SpecialForm() : $this->_loadModel((int)$id);
		$model->setScenario('admin');
		
		//authenticate id_admin
		if (!empty($id)) $this->_authenticate($model->id_admin);
		
		//check merchant id
		if (empty($id)) {
			$id_merchant = Yii::app()->request->getQuery('mid');
			$model->id_merchant = $id_merchant;
			$model->id_admin = Yii::app()->user->id; // add admin ID to new offer
		} else {
			$id_merchant = $model->id_merchant;
		}
		
		// if it is ajax validation request
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'special-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		
		// collect user input data
		if (isset($_POST['SpecialForm'])) {
			$model->attributes = $_POST['SpecialForm'];
			
			//get the merchant id
			$model->id_merchant = $_POST['SpecialForm']['id_merchant'];
			$model->content = strip_tags($_POST['SpecialForm']['content']);
			
			//offer date range
			$model->start_date = date('Y-m-d',strtotime($_POST['SpecialForm']['start_date']));
			if (empty($_POST['SpecialForm']['end_date'])) $model->end_date = $model->start_date;
			else $model->end_date = date('Y-m-d',strtotime($_POST['SpecialForm']['end_date']));
			$model->end_date .= ' 23:59:59';

			//set the url_picture
			$model->url_picture = $_POST['SpecialForm']['url_picture'];
			
			//set the time for each day
			for ($i=1; $i<8; $i++) {
				$filed_start = "day_{$i}_start_hour";
				$filed_end = "day_{$i}_end_hour";
				$model->$filed_start = new CDbExpression('NULL');
				$model->$filed_end = new CDbExpression('NULL');
			}
			if (!empty($_POST['offer_hours'])) {
				foreach ($_POST['offer_hours'] as $k => $v) {
					$filed_start = "day_{$k}_start_hour";
					$filed_end = "day_{$k}_end_hour";
					$aTemp = explode(',', $v);
					$model->$filed_start = $aTemp[1];
					$model->$filed_end = $aTemp[2];
				}
			}
			//set the old time style (for old offer)
			if (!empty($_POST['offer_hours'])) {
				$keys = array_keys($_POST['offer_hours']);
				sort($keys);
				$model->week_days = implode(',', $keys);
				foreach ($_POST['offer_hours'] as $k => $v) {
					$aTemp = explode(',', $v);
					$model->start_hour = $aTemp[1];
					$model->end_hour = $aTemp[2];
					break;
				}
			}
			
			//set offer price and discount
			if (!empty($_POST['SpecialForm']['price'])) {
				$model->price = $_POST['SpecialForm']['price'];
			} else {
				$model->price = new CDbExpression('NULL');
			}
			if (!empty($_POST['SpecialForm']['value'])) {
				$model->value = $_POST['SpecialForm']['value'];
			} else {
				$model->value = new CDbExpression('NULL');
			}
			if (!empty($_POST['SpecialForm']['discount'])) {
				$model->discount = $_POST['SpecialForm']['discount'];
			} else {
				$model->discount = new CDbExpression('NULL');
			}
			
			$model->type = 1;
			$model->redeem_type = 1; //all offer is for click to redeem
			$model->update_timestamp = new CDbExpression('NOW()');
			
			//get the browser info: client_type, agent_string
			$model->client_type = 'Web';
			$model->agent_string = Yii::app()->request->getUserAgent();
			
			if ($model->save()) {
				$url = $this->createUrl('index', array('id'=>$model->id));
				Yii::app()->request->redirect($url);
			} else {
				Yii::app()->user->setFlash('saved', 'System error was happen when you saved!');
				$this->refresh();
			}
		} else {
			//add sid=100980 to use the old offer's info
			$sid = Yii::app()->request->getQuery('sid');
			if (!empty($sid) and empty($id)) {
				$model_old = $this->_loadModel((int)$sid);
				$model->content = $model_old->content;
				$model->url_picture = $model_old->url_picture;
				$model->price = $model_old->price;
				$model->value = $model_old->value;
				$model->discount = $model_old->discount;
				$model->max_number = $model_old->max_number;
				$model->type = $model_old->type;
				//keep the hours range
				$model->start_hour = $model_old->start_hour;
				$model->end_hour = $model_old->end_hour;
				$model->week_days = $model_old->week_days;
				
				//if $id_merchant == null
				if (empty($id_merchant)) {
					$id_merchant = $model_old->id_merchant;
					$model->id_merchant = $id_merchant;
				}
			}
			
			$connection = Yii::app()->db;
			//get merchant's profile and the current day open hours
			$row = array();
			$merchant_hours = array();
			if (!empty($model->id_merchant)) {
				$sql_merchant = ' SELECT m.id, m.name, m.address, m.postcode, m.phone, m.city, m.country_code, m.currency_code,
				m.url_logo, m.url_site, m.url_offer_img
				FROM tbl_merchant_account m
				WHERE m.id=:id ';
				$command = $connection->createCommand($sql_merchant);
				$row = $command->queryRow(true, array(':id'=>$model->id_merchant));

				//fetch merchant's open hours
				$sql_hours = 'SELECT week_no, open_hour, close_hour FROM tbl_merchant_open_hours
					WHERE id_merchant=:id_merchant ORDER BY week_no ASC';
				$command = $connection->createCommand($sql_hours);
				$aHours = $command->queryAll(true, array(':id_merchant'=>$model->id_merchant));
				$merchant_hours = array();
				foreach ($aHours as $hour) {
					$merchant_hours[(int)$hour['week_no']] = $hour;
				}
				unset($aHours);
			}
			
			//get the template content
			$templateId = Yii::app()->request->getQuery('tid');
			if (!empty($templateId)) {
				$sql_template = 'SELECT t.url_picture, t.content, t.price, t.value, t.discount
					FROM tbl_merchant_special_template t
					WHERE t.id_merchant=:id_merchant AND t.id=:id ';
				$command = $connection->createCommand($sql_template);
				$tempRow = $command->queryRow(true, array(':id_merchant'=>$id_merchant, ':id'=>$templateId));
				$model->content = $tempRow['content'];
				$model->url_picture = $tempRow['url_picture'];
				$model->price = $tempRow['price'];
				$model->value = $tempRow['value'];
				$model->discount = $tempRow['discount'];
			}
			$connection->active = false;
			
			//set the offer_hours array
			$using_old_time = true;
			$offer_hours = array();
			for ($i=1; $i<8; $i++) {
				$field_start = "day_{$i}_start_hour";
				$field_end = "day_{$i}_end_hour";
				$offer_hours[$i] = array(
					'start_hour' => $model->$field_start,
					'end_hour'=> $model->$field_end,
				);
				if ($model->$field_start !== null)  {
					$using_old_time = false;
				}
			}
			if (empty($id)) {
				//if this is new offer, then use the business hours
				for ($i=1; $i<8; $i++) {
					if ($offer_hours[$i]['start_hour'] === null or $offer_hours[$i]['start_hour'] === '') {
						$offer_hours[$i]['start_hour'] = (isset($merchant_hours[$i]['open_hour'])) ? $merchant_hours[$i]['open_hour'] : null;
						$offer_hours[$i]['end_hour'] = (isset($merchant_hours[$i]['close_hour'])) ? $merchant_hours[$i]['close_hour'] : null;
					}
				}
			} elseif($using_old_time) {
				//use the old way
				foreach (explode(',', $model->week_days) as $weekNo) {
					$offer_hours[$weekNo] = array('start_hour'=>$model->start_hour, 'end_hour'=>$model->end_hour);
				}
			}
			
			
			$model->type = 1;//must set to 1
			$model->redeem_type = 1; //all offer is for click to redeem
			$row['thumbs'] = array();//TODO: Here we can add thumbs for this offer.
			$this->render('form', array('model' => $model, 'r'=>$row, 'offer_hours'=>$offer_hours));
		}
	}
	
	/**
	 * Insert url_offer_img picture with AJAX.
	 * 96x96 + 640x320
	 */
	public function actionUploadOfferImage()
	{
		/*
		 * This AJAX verification should not enable due to the uploading component.
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		*/
		$id_merchant = Yii::app()->request->getParam('mid');
		if (empty($id_merchant)) {
			throw new CHttpException(500, 'The merchant ID is missing!');
		}
		
		$specialId = Yii::app()->request->getParam('id');
		if (empty($specialId)) {
			$specialId = time();
		}
		$specialId .= rand(100, 999);
		
		//set folder
		$saved_folder = BUtils::GetUploadingFolder($id_merchant);
		$url_folder = BUtils::GetUploadingUrl($id_merchant);
		
		Yii::import("ext.EAjaxUpload.qqFileUploader");
		$allowedExtensions = array("jpg","jpeg","gif","png");
		$sizeLimit = 8 * 1024 * 1024;
		$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
		$result = $uploader->handleUpload($saved_folder, 'offer_' . $specialId, true);
		unset($uploader);
		
		//set thumb
		$thumb = 'thumb_' . $result['filename'];
		//resize offer picture to 640 x 360 size:
		Yii::import('ext.iwi.Iwi');
		$picture = new Iwi($saved_folder . $result['filename']);
		// resize to 640x360: 16:9
		$picture->adaptive(640, 360);
		$picture->save($saved_folder . $result['filename']);
		// resize to 108x108
		$picture->adaptive(192, 108);
		$picture->crop(108, 108);
		$picture->save($saved_folder . $thumb);
		unset($picture);
		
		$result['url_offer_img'] = BUtils::GetPictureUrl($url_folder . $result['filename']) . '?t=' . time();
		$result['url_offer_img_db'] = $url_folder . $thumb;
		echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
	}
	
	/**
	 * AJAX publish a special.
	 */
	public function actionPublish($id) {
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		//update status=1, published_time=NOW() (only for status=0)
		$connection = Yii::app()->db;
		$command = $connection->createCommand('UPDATE tbl_merchant_special SET status=1, published_time=NOW() WHERE id=:id AND status=0');
		$command->execute(array(':id'=>$id));
		
		//update the admin id
		$command = $connection->createCommand('UPDATE tbl_merchant_special SET id_admin=:id_admin WHERE id=:id AND id_admin IS NULL');
		$command->execute(array(':id'=>$id, ':id_admin'=>Yii::app()->user->id));
		$connection->active = false;
	}
	
	/**
	 * AJAX delete an offer.
	 */
	public function actionDelete($id) {
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		//delete current special (only for status=0)
		$connection = Yii::app()->db;
		$command = $connection->createCommand('UPDATE tbl_merchant_special SET trash=1, trash_time=NOW() WHERE id=:id AND id_admin=:id_admin');
		$num = $command->execute(array(':id'=>$id, ':id_admin'=>Yii::app()->user->id));
		$connection->active = false;
		
		echo BUtils::sendJSON(200, $num);
	}

	public function actionPreview($id) {
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		$sql_offer = 'SELECT s.id, s.id_merchant, s.url_picture, s.content, m.url_offer_img, 
			s.price, s.value, s.discount, s.show_hours, s.start_hour, s.end_hour, s.week_days, s.type, s.max_number, s.redeem_type,
			day_1_start_hour, day_2_start_hour, day_3_start_hour, day_4_start_hour, day_5_start_hour, day_6_start_hour, day_7_start_hour,
			day_1_end_hour, day_2_end_hour, day_3_end_hour, day_4_end_hour, day_5_end_hour, day_6_end_hour, day_7_end_hour,
			UNIX_TIMESTAMP(s.published_time) AS uts_published_time,
			UNIX_TIMESTAMP(s.start_date) AS uts_start_date, UNIX_TIMESTAMP(s.end_date) AS uts_end_date,
			m.name, m.address, m.biz_area, m.postcode, m.city, m.phone, m.url_logo, m.currency_code, m.category_key, m.latitude, m.longitude
			FROM tbl_merchant_special s
			INNER JOIN tbl_merchant_account m ON m.id=s.id_merchant
			WHERE s.id=:id ';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_offer);
		$row = $command->queryRow(true, array(':id'=>$id));
		$connection->active = false;
		
		//search for thumbs
		$row['thumbs'] = array();
		
		if (empty($row)) {
			throw new CHttpException(404, 'The requested page does not exist.');
		}
		
		//set the offer_hours array
		$using_old_time = true;
		$offer_hours = array();
		for ($i=1; $i<8; $i++) {
			$field_start = "day_{$i}_start_hour";
			$field_end = "day_{$i}_end_hour";
			$offer_hours[$i] = array(
				'start_hour' => $row[$field_start],
				'end_hour'=> $row[$field_end],
			);
			if ($row[$field_start] !== null)  {
				$using_old_time = false;
			}
		}
		if($using_old_time) {
			//use the old way
			foreach (explode(',', $row['week_days']) as $weekNo) {
				$offer_hours[$weekNo] = array('start_hour'=>$row['start_hour'], 'end_hour'=>$row['end_hour']);
			}
		}
		
		$this->renderPartial('_preview', array('r' => $row, 'offer_hours'=>$offer_hours));
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	protected function _loadModel($id) {
		$condition = '';
		if (Yii::app()->user->sys_role != 0) {
			$condition = 'id_admin=' . Yii::app()->user->id;
		}
		
		$model = SpecialForm::model()->findByPk(
			$id, $condition
		);
		if ($model===null) throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}
	
	protected function _authenticate($id_admin) {
		if ((int)Yii::app()->user->sys_role !== 0) {
			if (Yii::app()->user->id != $id_admin)
				throw new CHttpException(404, 'You dont have permission to edit this offer!');
		}
	}
}